package com.ihrm.system.controller;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.system.User;
import com.ihrm.system.client.DepartmentFeignClient;
import com.ihrm.system.dao.UserDao;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@RestController
public class CommonTroller extends BaseController {

    //设置APPID/AK/SK
    public static final String APP_ID = "45689830";
    public static final String API_KEY = "9RDDxmEfWnkDIlDPCiLX6faK";
    public static final String SECRET_KEY = "OfZ5RqGtMTXSsYkGNv9dx6NOb7ZGgFMO";

    @Autowired
    private UserDao userDao;

    @Autowired
    private DepartmentFeignClient departmentFeignClient;


    //人脸注册
    @PostMapping("/face/register")
    public void faceRegister() throws IOException {
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
//        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE"); //默认APPEND userid相同是替换或者新增

        String imageType = "BASE64";
        String groupId = "itcast";
        String userId = "1000";
        //构造base64图片字符串
        String path = "C:\\Users\\xe79\\Desktop\\资源\\照片\\001.png";
        byte[] bytes = Files.readAllBytes(Paths.get(path));
        String image = Base64Util.encode(bytes);
        // 人脸注册
        JSONObject res = client.addUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));
    }
//
//    //人脸更新
//    @PostMapping("/face/update")
//    public void faceUpdate() throws IOException {
//        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
//        // 传入可选参数调用接口
//        HashMap<String, String> options = new HashMap();
//        options.put("face_field", "age");
//        options.put("max_face_num", "2");
//        options.put("face_type", "LIVE");
//        options.put("liveness_control", "LOW");
//
//        String groupId = "itcast";
//        String userId = "1000";
//        String imageType = "BASE64";
//
//        String path = "C:\\Users\\xe79\\Desktop\\资源\\照片\\002.png";
//        byte[] bytes = Files.readAllBytes(Paths.get(path));
//        String image = Base64Util.encode(bytes);
//        // 人脸更新
//        JSONObject res = client.updateUser(image, imageType, groupId, userId, options);
//        System.out.println(res.toString(2));
//    }


    //人脸查找
    @PostMapping("/face/search")
    public void faceSearch() throws IOException {
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap();

        options.put("max_face_num", "2");
        options.put("quality_control", "NORMAL");
        options.put("match_threshold", "70");
        options.put("liveness_control", "LOW");

        String groupId = "itcast";
        String userId = "1000";
        String imageType = "BASE64";

        String path = "C:\\Users\\xe79\\Desktop\\资源\\照片\\002.png";
        byte[] bytes = Files.readAllBytes(Paths.get(path));
        String image = Base64Util.encode(bytes);
        // 人脸更新
        JSONObject res = client.updateUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));
    }

    /**
     * 导入Excel，添加用户
     * 文件上传：SpringBoot
     */
    @PostMapping("/user/import")
    public Result importUser(MultipartFile file) throws Exception {
        //用户名 手机号 工号 聘用形式 入职时间 部门编码
        //1.1.根据Excel文件创建工作簿
        Workbook wb = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = wb.getSheetAt(0);//参数：索引
        List<User> list = new ArrayList<>();
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {  //从第二行开始读取，索引是1
            Row row = sheet.getRow(rowNum);//根据索引获取每一个行
            User user = new User();
            for (int cellNum = 1; cellNum < row.getLastCellNum(); cellNum++) {
                Cell cell = row.getCell(cellNum);
                Object value = getValue(cell);
                if (cellNum == 1) {
                    user.setUsername((String) value);
                }
                if (cellNum == 2) {
                    user.setMobile(new DecimalFormat("#").format(value).toString());
                }
                if (cellNum == 3) {
                    user.setWorkNumber(new DecimalFormat("#").format(value).toString());
                }
                if (cellNum == 4) {
                    user.setFormOfEmployment(((Number) value).intValue());
                }
                if (cellNum == 5) {
                    user.setTimeOfEntry((Date) value);
                }
                if (cellNum == 6) {
                    Department dept = departmentFeignClient.findByCondition((String) value);
                    user.setDepartmentId(dept.getId());
                    user.setDepartmentName(dept.getName());
                }
                user.setId(new IdWorker().nextId() + "");
                user.setCorrectionTime(new Date());
                user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            }
            list.add(user);
        }
        //3.批量保存用户
        Integer num = userDao.insertBatch(list);
        if (num > 0) {
            return Result.SUCCESS();
        } else {
            return Result.FAIL();
        }

    }

    /**
     * 根据传入的cell判断单元格中内容的格式,从而获取到相应的值
     */
    public static Object getValue(Cell cell) {
        //获取单元格的属性
        CellType cellType = cell.getCellType();
        //根据单元格属性获取数据
        Object value = null;
        switch (cellType) {
            case STRING:
                value = cell.getStringCellValue();
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //日期
                    value = cell.getDateCellValue();
                } else {
                    //数字
                    value = cell.getNumericCellValue();
                }
                break;
            case FORMULA:   //公式
                value = cell.getCellFormula();
        }
        return value;
    }


}
